<?php

namespace Admin\Controller;

use Think\Controller;
use Think\Auth;

class CommonController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->address = M('Address');
        $this->customer_id = $_SESSION['customer']['id'];
        $this->order_product = M('Order_product');
        $this->order= M('Orders');
        $this->product= M('Product');
        $this->check_login();
        $this->all_rules();
    }

    /***
     * 检查用户是否登录
     */
    public function check_login()
    {
        $user = $_SESSION['user'];
        if (isset($_SESSION['user'])) {
            $this->assign('user', $_SESSION['user']);
        }


        //如果cookie不存在。调到登录页
        if (!isset($_COOKIE['token'])) {
            $this->error('您还没有登录，请登录', U('User/login'));
        }
        //如果cookie与数据库的不匹配，表示用户伪造了tooken
        $token = $_COOKIE['token'];
        $User = M('User');
        $user = $User->where("token = '$token'")->find();
        if (!$user) {
            $this->error('请不要非法登录', U('User/login'));
        }

        //当前面的各个模块的增删改查完成后，开启下面的代码即可实现权限管理
//        $Auth = new Auth();
//        $name = MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME;
//        if (!$Auth->check($name, $user['id'])) {
//            $this->error('您没有权限访问当前页面,请与管理员联系', U('User/no_auth'));
//        }

        $_SESSION['user'] = $user;
        $this->assign('user', $_SESSION['user']);

    }

    /***
     * 查出所有权限
     */
    public function all_rules()
    {
        $AuthRule = M('AuthRule');

        //一级菜单
        $rules = $AuthRule->where("parent_id = 0")->select();
        //二级菜单
        foreach ($rules as $key => $value) {
            $children = $AuthRule->where("parent_id = '$value[id]'")->select();
            $rules[$key]['children'] = $children;

            //三级菜单
            foreach ($rules[$key]['children'] as $k =>$v){
                $child = $AuthRule->where("parent_id = '$v[id]'")->select();
                $rules[$key]['children'][$k]['child'] = $child;
            }
        }

//        p($rules);exit;
        $this->assign(compact('rules'));

    }


}
